package yxy.game.pm2.command.stairway;

import yxy.cherry.data.script.fomula;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.StairwayMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.stairway.StairwayHandle;
import yxy.game.pm2.module.stairway.StairwayPlayerModule;

/** 天梯争雄 天梯购买挑战次数 */
@MessageType(proto = Command.StairwayPurchase, classtype = StairwayMessage.StairwayPurchaseRequest.class)
public class CMD_StairwayPurchase extends Command<StairwayMessage.StairwayPurchaseRequest> {

	@Override
	public void execute(MessageSource messageSource, StairwayMessage.StairwayPurchaseRequest request) {
		String playerCode = messageSource.getTag();

		StairwayMessage.StairwayPurchaseResponse.Builder response = StairwayMessage.StairwayPurchaseResponse.newBuilder();

		PlayerBean playerBean = PlayerBean.get(playerCode);
		ServerBean serverBean = ServerBean.get(playerBean.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());
		boolean isOpen = StairwayHandle.isOpen(areaBean.getGroupId());
		if (!isOpen) {
			send(messageSource, response, Result.StairwayNotOpen);// 活动没有开始
			return;
		}
		StairwayPlayerModule stairwayPlayerModule = StairwayPlayerModule.get(playerCode);
		if (stairwayPlayerModule == null) {
			send(messageSource, response, Result.ModuleNotOpen);
			return;
		}

		// TODO 加锁
		int costNum = fomula.天梯争雄购买次数元宝花费.intValue(stairwayPlayerModule.getBuytimes());
		Currency cost = Currency.create(CurrencyType.CT_元宝, 0, costNum);
		try {
			new CurrencyHandle().cost(stairwayPlayerModule.getPlayerCode(), CCReason.天梯争雄, cost);
		} catch (CurrencyNotEnoughException e) {
			Result result = new Result(Result.CostFail, e.getType().getNumber(), e.getDataId());// 消费不足
			send(messageSource, response, result);
			return;
		}
		stairwayPlayerModule.setTimes(stairwayPlayerModule.getTimes() - 1);
		stairwayPlayerModule.setBuytimes(stairwayPlayerModule.getBuytimes() + 1);
		stairwayPlayerModule.set();

		response.setTimes(stairwayPlayerModule.remainTimes());
		response.setBuytimes(stairwayPlayerModule.remainBuyTimes());

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, StairwayMessage.StairwayPurchaseResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}